package nina.yiyou.salary.input.info


import luj.groovy.excel.api.LugExcel
import luj.groovy.excel.api.table.Table
import luj.groovy.excel.api.table.body.Row
import luj.groovy.excel.api.table.header.Header
import luj.groovy.excel.api.table.header.HeaderField
import nina.yiyou.salary.input.util.ExcelReadOpener
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook

import java.util.stream.Collectors

/**
 * 读取考勤表
 */
class AttendExcelV2Reader {

  AttendExcelV2Reader(String excelPath) {
    _excelPath = excelPath
  }

  Map<String, Map> read() {
    Workbook workbook = new ExcelReadOpener(_excelPath).openXlsx()
    Map result = readImpl(workbook.getSheetAt(0))
    workbook.close()
    return result
  }

  private Map<String, Map> readImpl(Sheet sheet) {
    Table table = LugExcel.table(sheet).header {
      startCell('A1')
      rowSize(1)
    }.build()

    String idKey = COL.values().first()
    return table.body.rows.stream()
        .map { makeLine(it, table.header) }
        .collect(Collectors.toMap({ it[idKey] }, { it }))
  }

  private Map<String, ?> makeLine(Row row, Header header) {
    def getField = { String f ->
      HeaderField name = header.getField(f)
      assert name != null, "找不到列：${f}"
      return row.getFieldValue(name)
    }

    return COL.entrySet()
        .collectEntries { [it.getValue(), getField(it.getKey())] }
  }

  private static final Map<String, String> COL = [
      '基本.工号'   : '工号',
      '明细.姓名'   : '姓名',
      '无.本月计薪'  : '应出勤',
      '计算2.试用应计': '试用应出勤',
      '计算2.试用实计': '试用实际出勤',
      '计算2.转正应计': '转正应出勤',
      '计算2.转正实计': '转正实际出勤',
      '无.全勤'    : '全勤',
  ]

  private final String _excelPath
}
